//
//  NetWorkRequest.m
//  CI
//
//  Created by tongbu_jinzhongjun on 14-10-20.
//  Copyright (c) 2014年 tongbu_jinzhongjun. All rights reserved.
//

#import "NetWorkRequest.h"
#import <Objection.h>
#import "NetWork.h"
#import "UpdateDatabase.h"
#import "UserDefaultSave.h"


@implementation NetWorkRequest
objection_register_singleton(NetWorkRequest)

-(void)loginWithParameter:(id)parameter success:(void (^)())loginSuc failure:(void (^)())loginFail {

    [NetWork post:[self urlStringWithCall:@"login"] parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dictionary);
        
        if ([[dictionary objectForKey:@"loginState"] integerValue] == 0) {
            loginFail();
        }else {
            loginSuc();
            
            dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
            dispatch_group_t group = dispatch_group_create();
            
            UpdateDatabase *update_database = [[JSObjection defaultInjector] getObject:[UpdateDatabase class]];
            dispatch_group_async(group, queue, ^{
                [update_database deleteAllUserData];
            });
            
            dispatch_group_notify(group, dispatch_get_main_queue(),  ^{
                
                NSArray *hospital_array = [dictionary objectForKey:@"hospital"];
                for (NSDictionary *dic in hospital_array) {
                    [update_database updateHospitalWithDic:dic];
                }
                
                NSArray *type_array = [dictionary objectForKey:@"type"];
                for (NSDictionary *dic in type_array) {
                    [update_database updateTypeWithDic:dic];
                }
                
                NSArray *company_array = [dictionary objectForKey:@"company"];
                for (NSDictionary *dic in company_array) {
                    [update_database updateCompanyWithDic:dic];
                }
                
                NSArray *userProduct_array = [dictionary objectForKey:@"userProduct"];
                for (NSDictionary *dic in userProduct_array) {
                    [update_database updateUserProductWithDic:dic];
                }
                
                UserDefaultSave *save_user_id = [[JSObjection defaultInjector] getObject:[UserDefaultSave class]];
                [save_user_id saveUserId:[dictionary objectForKey:@"userId"]];
            });
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        loginFail();
    }];
}

-(void)updateDataWithParameter:(id)parameter success:(void (^)())loginSuc failure:(void (^)())loginFail {
    [NetWork post:[self urlStringWithCall:@"update"] parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

-(NSString*)urlStringWithCall:(NSString*) call {
    return [NSString stringWithFormat:@"%@%@",BaseUrl,call];
}

-(void)postProductInfoWithHospitalId:(NSString *)hospitalId typeId:(NSString *)typeId companyId:(NSString *)companyId productId:(NSString *)productID count:(NSString *)count {
    
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSDictionary *dictionary = @{@"hospitalId":hospitalId,
                                 @"typeId":typeId,
                                 @"companyId":companyId,
                                 @"userId":userId,
                                 @"productId":productID,
                                 @"count":count};
    [self postProductInfoWithParameter:dictionary success:^{
        
    } failure:^{
        
    }];
}

-(void)postProductInfoWithParameter:(id)parameter success:(void (^)())updateSuc failure:(void (^)())updateFailure{
    [NetWork post:[self urlStringWithCall:@"update"] parameters:parameter
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              
              NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
               NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
              NSLog(@"向服务器提交数据成功！string:%@",string);
              if ([[dictionary objectForKey:@"state"] integerValue] == 1) {
                  updateSuc();
              }else {
                  updateFailure();
              }
              
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSLog(@"向服务器提交数据失败：ERROR:%@",error);
          }];

}


@end
